package redis

import (
	"fmt"
	"github.com/go-redis/redis/v8"
	"sync"
	"telemple_web/app/core/config"
)

var redisClientSyncMap = make(map[string]*redis.Client)
var redisClientMutex sync.RWMutex

func Load(flag string, conf *config.Model, key ...string) *redis.Client {
	var k = "default"
	if len(key) > 0 {
		k = key[0]
	}

	sgKey := flag + "_" + k
	redisClientMutex.RLock()
	if c, ok := redisClientSyncMap[sgKey]; ok {
		redisClientMutex.RUnlock()
		return c
	}
	redisClientMutex.RUnlock()
	redisClientMutex.Lock()
	defer redisClientMutex.Unlock()

	if c, ok := redisClientSyncMap[sgKey]; ok {
		return c
	}

	rdsConfig, ok := conf.Redis[k]
	if !ok {
		panic(fmt.Sprintf("redis key:%s config not exists: ", k))
	}
	c := initRedis(flag == "write", &rdsConfig)

	redisClientSyncMap[sgKey] = c
	return c
}

func initRedis(isWrite bool, conf *config.Redis) *redis.Client {
	var rdsConfig config.RedisEle
	if isWrite {
		rdsConfig = conf.Write
	} else {
		rdsConfig = conf.Read
	}
	fmt.Println("rdsConfig:", rdsConfig)
	return redis.NewClient(&redis.Options{
		Addr:         rdsConfig.Addr,
		PoolSize:     rdsConfig.PoolSize,
		Password:     rdsConfig.Password,
		IdleTimeout:  rdsConfig.IdleTimeout,
		ReadTimeout:  rdsConfig.ReadTimeout,
		WriteTimeout: rdsConfig.WriteTimeout,
		MaxRetries:   rdsConfig.MaxReConnect,
		MinIdleConns: rdsConfig.MinIdleConnections,
		DB:           rdsConfig.DB,
	})
}
